package org.liquidByte.trafficMustang.androidApp;

import org.liquidByte.trafficMustang.R;
import org.liquidByte.trafficMustang.androidApp.activities.AbstractActivity;
import org.liquidByte.trafficMustang.androidApp.activities.MainActivity;
import org.liquidByte.trafficMustang.androidApp.proxy.Proxy;
import org.liquidByte.trafficMustang.androidApp.proxy.ProxyConfig;
import org.liquidByte.trafficMustang.androidApp.proxy.RemoteException;
import org.liquidByte.trafficMustang.androidApp.services.Services;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Application;
import android.content.DialogInterface;
import android.widget.Toast;

public class App extends Application {
	
	private static App instance;
	
	public static App getInstance() {
		return instance;
	}

	public static void error(Exception e) {
		if (e instanceof RemoteException) {
			App.error((RemoteException)e);
		} else {
			App.error(e.getMessage());
		}
	}
	
	public static void error(RemoteException e) {
		String message = e.getMessage();
		if (message == null || message.equals("")) {
			message = e.getExceptionType();
		}
		App.error(message);
	}
	
	public static void error(String message) {
		Builder builder = new Builder(AbstractActivity.getCurrent());
		builder.setTitle(R.string.msgs_erro)
			   .setCancelable(false)
			   .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
															@Override
															public void onClick(DialogInterface dialog, int which) { }
													   }
			   );
		if (message == null || message.equals("")) {
			builder.setMessage(R.string.msgs_indisponivel);
		} else {
			builder.setMessage(message);
		}
		AlertDialog dialog = builder.create();
		dialog.show();
	}
	
	public static void validationError(String error) {
		if (error != null && !error.equals("")) {
			Toast toast = Toast.makeText(MainActivity.getInstance(), error, Toast.LENGTH_SHORT);
			toast.show();
		}
	}

	@Override
	public void onCreate() {
		super.onCreate();
		
		App.instance = this;
		
		Config.create(this);
		Config.getInstance().setChangedActionListener(new Config.PreferencesChanged() {
			
			@Override
			public void onChanged(Config config) {
				ProxyConfig.create(config.getContextRoot());
			}
		});
		ProxyConfig.create(Config.getInstance().getContextRoot());
		LocationTracker.getInstance().setLocationListener(Services.getLocationListener());
	}
	
	public static void cleanUp() {
		LocationTracker.cleanUp();
		Services.cleanUp();
		Proxy.cleanUp();		
	}
}
